/*
** b_cd.c for 42sh in /home/lingla_j/work/projet/minishell2/minishell2-2016-lingla_j
** 
** Made by julien linglain
** Login   <lingla_j@epitech.net>
** 
** Started on  Thu Mar 22 14:30:36 2012 julien linglain
** Last update Sat Mar 31 15:15:21 2012 julien linglain
*/

#include <stdlib.h>
#include <unistd.h>
#include <sys/stat.h>
#include <string.h>
#include "mysh.h"

char		*make_path(char *s, char *pwd)
{
  char		*path;
  char		*pwd_cpy;

  pwd_cpy = my_strcpy(pwd);
  path = strncat(pwd_cpy, "/", 1);
  path = strncat(pwd_cpy, s, my_strlen(s));
  return (path);
}

char		*gohome(t_list *env)
{
  char		*home;

  home = getvalue(env, "HOME");
  if (home != NULL)
    return (home);
  else
    return ("/");
}

char		*goback(t_list *env, char *pwd)
{
  char		*back;

  back = getvalue(env, "OLDPWD");
  if (back != NULL)
    return (back);
  else
    return (pwd);
}

char		*cd_with_var(t_list *env, char *var, char *pwd)
{
  char		*path;
  char		*epur_var;
  char		*value;

  if (my_strlen(var) > 1)
    {
      epur_var = get_var(var);
      value = getvalue(env, epur_var);
      free(epur_var);
      if (value == NULL)
	return (NULL);
      if (check_exist_access(value) == 1)
        {
          cd_error(value);
          return (NULL);
        }
      else
	return (value);
    }
  else
    {
      cd_error("$");
      return (NULL);
    }
}

int		my_cd(int ac, char *s, char **av, t_list *env)
{
  char		*pwd;
  char		*path;

  pwd = get_current_dir_name();
  if (ac == 1 || my_strcmp(av[1], "~") == 0)
    path = gohome(env);
  else if (ac != 1 && my_strcmp(av[1], "-") != 0 && av[1][0] != '$')
    {
      if (check_exist_access(av[1]) == 1)
	{
	  cd_error(av[1]);
	  return (EXIT_FAILURE);
	}
      if (av[1][0] != '/' && ac > 1)
	path = make_path(av[1], pwd);
      else
	path = my_strcpy(av[1]);
    }
  else if (ac != 1 && av[1][0] == '$')
    path = cd_with_var(env, av[1], pwd);
  else
    path = goback(env, pwd);
  my_chdir(env, pwd, path);
  return (EXIT_SUCCESS);
}
